package sword.T67;

/**
 * @Author: 18362
 * @Create: 2022-04-10 20:38:34 星期日
 */
class Solution {
    public int strToInt(String str) {
        char[] chars = str.toCharArray();
        int start = 0;
        while (start < chars.length && chars[start] == ' ') {
            start++;
        }
        if (start == chars.length)
            return 0;
        boolean flag = true;
        if (chars[start] == '+')
            start++;
        else if (chars[start] == '-') {
            flag = false;
            start++;
        }
        if (start == chars.length || !(chars[start] >= '0' && chars[start] <= '9'))
            return 0;
        int res = 0;
        while (start < chars.length && (chars[start] >= '0' && chars[start] <= '9')) {
            int m = chars[start++] - '0';
            if (flag) {
                int t = res * 10 + m;
                if (t < res || (t - m) / 10 != res)
                    return Integer.MAX_VALUE;
                res = t;
            } else {
                int t = res * 10 - m;
                if (t > res || (t + m) / 10 != res)
                    return Integer.MIN_VALUE;
                res = t;
            }
        }
        return res;
    }
}
